#pragma once
#include <iostream>
#include <sys/epoll.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory>
#include "Socket.hpp"
#include "log.hpp"

extern LOG lg;

class Epoller {
    const static int defaultsize = 64;
public:
    Epoller()
    {
        _epfd = epoll_create(defaultsize);
        if(_epfd < 0)
        {
            lg(FATAL, "epoll_create1 error");
        }
    }
    //这个函数负责处理红黑树的添加，删除
    int EpollUpdate(int oper,int sockfd, uint32_t events)
    {
        int n=0;
        if(oper==EPOLL_CTL_ADD)
        {
            struct epoll_event ev;
            ev.events = events;
            ev.data.fd = sockfd;//方便后面知道哪一个fd就绪
            n=epoll_ctl(_epfd, oper, sockfd, &ev);
            if(n<0)
            {
                lg(FATAL, "epoll_ctl error");
            }
        }
        else
        {
            //oper==EPOLL_CTL_MOD||oper==EPOLL_CTL_DEL
            n=epoll_ctl(_epfd, oper, sockfd, nullptr);
            if(n<0)
            {
                lg(FATAL, "epoll_ctl error");
            }
        }
        return n;
    }

    int EpollWait(struct epoll_event *events, int maxevents, int timeout)
    {
        int n=epoll_wait(_epfd, events, maxevents, timeout);
        if(n<0)
        {
            lg(FATAL, "epoll_wait error");
        }
        return n;
    }
    ~Epoller()
    {
        if(_epfd > 0)
        {
            close(_epfd);
        }
    }
private:
    int _epfd;//epoll实例,创建epoll返回一个句柄（类似于文件）
};
